<?php
/**
 * PUrl class
 * This class is used to get, check url
 *
 * @author Patrice Ferlet <metal3d@copix.org> 
 * @package utils
 * @license http://opensource.org/licenses/lgpl-3.0.html GNU Lesser General Public License Version 3.0 (LGPLv3)
*/

class PUrl {

    /**
    * Return well formed url
    *
    * @param string path
    * @param array arguemnts
    * @return string url
    */
    public function get($path="", $args=array()){
        $url = "";
        switch($path){
            case '#':
                $url = $_SERVER['REQUEST_URI'];
                $url .= (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING'])) ? '?'. $_SERVER['QUERY_STRING'] : '';
                break;
            default:
                $url=$path;
        }
        $params = "";
        $first = true;
        foreach ($args as $key=>$val){
            if(!$first) $params .= "&";
            $params .= "$key=$val";
        }
        $params = (strlen($params)) ? '?'.$params : '';
        return $url.$params;
    }

    public function resource($resource){
        $resource = trim($resource);

        //check resource into module, then into theme, then in default... and then ?
        $moduledir = _config()->get('root/paths')->name('modules@path');
        $module    = _kernel()->getParam('module');
        $webroot   = _config()->get('root/paths')->name('webroot@path');
        $themepath   = _config()->get('root/paths')->name('theme@path');

        if (isset($_SERVER['PWD']))
            $webroot   = str_replace('__PWD__',$_SERVER['PWD'], $webroot);
        else
            $webroot   = str_replace ('__PWD__','.', $webroot);

        //check theme
        if(file_exists($themepath.'/'.$module.'/'.$resource)){
            $path = $themepath.'/'.$module.'/'.$resource;
        }
        //check in module
        elseif(file_exists($moduledir.'/'.$module.'/www/'.$resource)){
            $path = $moduleir.'/'.$module.'/www/'.$resource;
        }
        elseif(file_exists($themepath.$resource)){
            $path = $themepath.$resource;
        }
        //check "PWD"/www
        elseif(file_exists($webroot.'/'.$resource)){
            $path = $webroot.'/'.$resource;
        }

        return Purl::get('resource.php',array('path'=>$path));
        
    }


}
